// pages/baoliao/new/index.js
const app = getApp()
const root = app.globalData.url 
const http = require('../../utils/http.js');
import regeneratorRuntime from '../../lib/runtime/runtime'
let util = require('../../utils/util.js')
import { chooseImage,chooseVideo,uploadFile,showModal} from '../../utils/asyncwx.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',//标题
    content: '',//内容
    titleCount: 0, //标题字数
    contentCount: 0, //正文字数
    date: null,
    textareaBValue: '',
    picker: [],
    index: 0,
    dtype: null,
    imgList: [],
    videoList:null,
    size:null,
    uid: '',
    tname:null,
    role:null  //是否有权限
  },
  PickerChange(e) {
    //发射台选择处理
   
    let index0 = e.detail.value
    this.setData({
      index: e.detail.value,
      dtype: this.data.picker[index0].id,
    })
  
    //this.NewsItemsShow();
  },//end of PickerChange
  DateChange(e) {
    //日期选择处理
    this.setData({
      date: e.detail.value
    })
  },
  handleTitleInput(e) {
    //标题输入处理
    let value = e.detail.value
   
    this.setData({
      title: value
    })
    this.setData({
      titleCount: value.length //计算已输入的标题字数
    })
  },
  textareaBInput(e) {
    //内容输入处理
    const value = e.detail.value
    this.setData({
      content: value
    })
    this.setData({
      contentCount: value.length //计算已输入的内容字数
    })

  },
  async ChooseVideo(){
    //视频选择
   
    let res=await chooseVideo()   
    this.setData({
          videoList: res.tempFilePath,
          size: (res.size / (1024 * 1024)).toFixed(2)
    })
   
  }, //end of ChooseVideo
  async ChooseImage() {
    //图像选择
    let res=await chooseImage()
    
    if (this.data.imgList.length != 0) {
      // // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      this.setData({
        imgList: this.data.imgList.concat(res.tempFilePaths)
      })
    } else {
      this.setData({
        imgList: res.tempFilePaths
      })
    }
  },// end of ChooseImage

 
  async DelVideo(e) {
    let res=await showModal({content:'确定要删除此视频吗？',showCancel:false}) 
    if (res.confirm) {
      //this.data.imgList.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        videoList:null,
        size:null
      })
    }
  },// end of DelVideo
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  async DelImg(e) {
    let res=await showModal({content:'确定要删除这张图片吗？',showCancel:false}) 
    if (res.confirm) {
      this.data.imgList.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        imgList: this.data.imgList
      })
    }
  },// end of DelImg
  
  async dosubmit(){
    //提交数据
    let title = this.data.title
    let content = this.data.content
    let dtype = this.data.dtype
    let uid = this.data.uid
    let video = this.data.videoList
    let size = this.data.size
    wx.showLoading({
      title: '正在创建...',
      mask: true
    })
    let arr = []
    let shipin=''
   
    if (video) {
     
      let path=this.data.videoList
      let res=await uploadFile(
        root+'file/uploadVideo',
        path,
        'uploadvideo',
        {}
       )
      //  console.log('视频地址',JSON.parse(res.data))
       shipin=JSON.parse(res.data).data.imgurl //视频地址
    }
    // const arr = []
    try {
    
    // 将选择的图片组成一个Promise数组，准备进行并行上传
    for (let path of this.data.imgList) {

      let res=await uploadFile(
        root+'file/uploadPic',
        path,
        'uploadimg',
        {}
       )

    
     
      arr.push(JSON.parse(res.data).data.imgurl)
      
    }
  
    let url = 'news/add';
    let data = {
        title: title,
        content: content,
        dtype: dtype,
        imgs: arr,
        uid: uid,
        shipin: shipin,
        fstId: this.data.dtype
     }
     let res= await http.post(url,data)
    
     if (res=='ok'){
      wx.switchTab({
          url: '../../pages/all_error/index'
           })
     }
   
    } catch (error) {
      showModal({content:'上传错误!'+error,showCancel:false})
    }
    wx.hideLoading()

   

  },// end of dosubmit
  async submitForm(e) {

   
    

    let title = this.data.title
    let content = this.data.content   
    let size=this.data.size
    let role = wx.getStorageSync('role')  
   
    if (role != "2") {
      let res= await showModal({content:'请先完善您的个人信息！',showCancel:true})   
      if (res.confirm) {           
       wx.switchTab({
         url: '/pages/mine/index'
       })
      }    
       return false;
     }
    
  
    if (this.data.size > 10) {
      await showModal({content:'很抱歉，视频最大允许10M，当前为！'+ (this.data.size + 'M'),showCancel:false}) 
    
      return false;
     
    } 
   
    if (title && content) {
      this.dosubmit()
     
    } else {
     
      await showModal({content:'请输入所有必填项目!',showCancel:false}) 
    
      return false;
     
    }
  },
  initdate(){
    //日期初始化
    var DATE = util.formatDate(new Date());

    this.setData({

      date: DATE,

    });

  },// end of initdate
  async fetchtype() {
    //获取发射机类型及用户信息
   
    let url = 'fst/list';
    let data = {
      uid: this.data.uid
    }
    let res= await http.get(url)
    this.setData({
      picker: res.fstList,
      dtype: res.fstList[0].id,
      // tname: res.fstList[0].name
     
    });
   
  },// end of  fetchtype
  async gettoken(){
    //从后台获取token
    let url = 'wx/login/'

    let data = {
      uid: wx.getStorageSync('uid')       
    }
    
    let res= await http.post(url,data)
   
    if (res){
      if (res!=null) {
        wx.setStorageSync('token',res)
      } 
    }
   
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.gettoken()    
    const tname=wx.getStorageSync('tname')
    let uid = wx.getStorageSync('uid')  
    let role = wx.getStorageSync('role')
   
    this.setData({     
      uid,
      role,
      tname     
    })
   
    this.fetchtype()
    this.initdate()
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})